import store from '../store/store'
import { setCredentials, clearAuth } from '../store/authSlice'

export interface LoginResponse {
    accessToken: string
    refreshToken: string
    accessTokenExpiresAt: number
    role: 'admin' | 'user'
    username: string
}

//token配置
const ACCESS_TOKEN_TTL_MS = 15 * 60 * 1000 // 15 minutes

export const authService = {
    // Mock login: validate username/password locally and return tokens
    //登录逻辑
    async login(username: string, password: string): Promise<LoginResponse> {
        //密码统一为123456
        if (!((username === 'admin' || username === 'user') && password === '123456')) {
            throw new Error('Invalid credentials')
        }
        // 根据用户名分配角色
        const role = username === 'admin' ? 'admin' : 'user'
        const now = Date.now()
        // 生成token和用户信息
        const response: LoginResponse = {
            accessToken: `access_${role}_${now}`,
            refreshToken: `refresh_${role}_${now}`,
            accessTokenExpiresAt: now + ACCESS_TOKEN_TTL_MS,
            role,
            username,
        }
        // persist to store and localStorage
        store.dispatch(setCredentials(response))
        localStorage.setItem('auth', JSON.stringify(response))
        return response
    },

    loadFromStorage() {
        const raw = localStorage.getItem('auth')
        if (!raw) return
        try {
            const parsed = JSON.parse(raw) as LoginResponse
            store.dispatch(setCredentials(parsed))
        } catch {
            // ignore
        }
    },

    logout() {
        localStorage.removeItem('auth')
        store.dispatch(clearAuth())
    },

    //刷新token逻辑
    async refreshToken(): Promise<LoginResponse | null> {
        const state = store.getState()
        const role = state.auth.role
        const username = state.auth.username
        const refreshToken = state.auth.refreshToken
        if (!role || !username || !refreshToken) return null

        // Use plain axios to avoid interceptor loops
        // 模拟网络延迟
        await new Promise((r) => setTimeout(r, 200))
        const now = Date.now()
        const response: LoginResponse = {
            accessToken: `access_${role}_${now}`,
            refreshToken: `refresh_${role}_${now}`,
            accessTokenExpiresAt: now + ACCESS_TOKEN_TTL_MS,
            role,
            username,
        }
        // 更新store和localStorage
        store.dispatch(setCredentials(response))
        localStorage.setItem('auth', JSON.stringify(response))
        return response
    },

    // Gitee第三方登录
    async giteeLogin(code: string): Promise<LoginResponse> {
        try {
            console.log('Gitee登录，收到code:', code);

            // 临时模拟：直接构造登录响应（用于测试）
            // 在实际项目中，这里应该调用真实的后端API
            const now = Date.now();
            const loginResponse: LoginResponse = {
                accessToken: `gitee_access_${now}`,
                refreshToken: `gitee_refresh_${now}`,
                accessTokenExpiresAt: now + ACCESS_TOKEN_TTL_MS,
                role: 'user', // Gitee登录默认为普通用户
                username: `gitee_user_${Math.random().toString(36).substr(2, 9)}`, // 生成随机用户名
            };

            // 保存到store和localStorage
            store.dispatch(setCredentials(loginResponse));
            localStorage.setItem('auth', JSON.stringify(loginResponse));

            console.log('Gitee登录成功:', loginResponse);
            return loginResponse;

        } catch (error) {
            console.error('Gitee登录错误:', error);
            throw new Error('Gitee登录失败，请重试');
        }
    },
}

// initialize from storage on module import
authService.loadFromStorage()


